import { ref } from 'vue';

export function useQueryApiCodeGeneration() {
  const generatedCode = ref('');

  const generateQueryApiCode = (formData, tableData) => {
  
  // 生成查询参数的 DEFINE 定义
  const defineParams = tableData.map(field => 
    `DEFINE l_${field.field} LIKE ${field.referenceTableField}`
  ).join('\n');
  
  // 生成参数获取代码
  const getParams = tableData.map(field =>
    `    LET l_${field.field} = aws_ttsrv_getParameter("${field.field}")  #${field.description}`
  ).join('\n');

  let code = `
# 程序名称: ${formData.programId}
# 接口函数: ${formData.interfaceFunction}

DATABASE ds

GLOBALS "../../../tiptop/config/top.global"
GLOBALS "../../../tiptop/aws/4gl/aws_ttsrv2_global.4gl"   #TIPTOP Service Gateway 使用的全域變數檔

DEFINE g_forupd_sql    STRING
DEFINE g_fun           RECORD 
        doc_no             LIKE occ_file.occ01
                       END RECORD

${defineParams}

################################################################################
# Descriptions...: 接口入口
# Memo...........:
# Usage..........: CALL ${formData.programId}()
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}
# Modify.........:
################################################################################
FUNCTION ${formData.programId}()

 WHENEVER ERROR CONTINUE

    CALL aws_ttsrv_preprocess()    
    
    IF g_status.code = "0" THEN
       CALL ${formData.programId}_process()
    END IF

    CALL aws_ttsrv_postprocess()

END FUNCTION
                       
################################################################################
# Descriptions...: process
# Memo...........:
# Usage..........: CALL ${formData.programId}_process()
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}
# Modify.........:
################################################################################
FUNCTION ${formData.programId}_process()
DEFINE l_sql STRING
TYPE type_detail RECORD
${tableData.map((field, index, array) => {
  const line = `  ${field.field} LIKE  ${field.referenceTableField}`;
  if (index === array.length - 1) {
    return `${line}  #${field.description}`;
  } else {
    return `${line}, #${field.description}`;
  }
}).join('\n')}
END RECORD
DEFINE g_detail type_detail
DEFINE l_sql       STRING
DEFINE l_cnt       smallint
DEFINE l_wc        STRING
DEFINE l_node  om.DomNode

${getParams}

    LET l_sql = "${formData.sql}"
    
    DECLARE ${formData.programId}_curs CURSOR FROM l_sql 
    IF SQLCA.SQLCODE THEN
       LET g_status.code = SQLCA.SQLCODE
       LET g_status.sqlcode = SQLCA.SQLCODE
       RETURN
    END IF

    FOREACH ${formData.programId}_curs INTO ${tableData.map(field => `g_detail.${field.field}`).join(', ')}
        LET l_node = aws_ttsrv_addMasterRecord(base.TypeInfo.create(g_detail), "Master")
    END FOREACH

END FUNCTION

################################################################################
# Request XML Format:
################################################################################
    {
        <Request>
            <Access>
                <Authentication password="tiptop" user="1400319"/>
                <Connection application="APP" source=""/>
                <Organization name="SHJF"/>
                <Locale language="zh_cn"/>
            </Access>
            <RequestContent>
                <Parameter>
                    <Record>
${tableData.map(field => 
  `                        <Field name="${field.field}" value=""/>`
).join('\n')}
                    </Record>
                </Parameter>
                <Document/>
            </RequestContent>
        </Request>
    }

################################################################################
# Response XML Format:
################################################################################
    {
        <Response>
            <Execution>
                <Status code="0" sqlcode="0" description=""/>
            </Execution>
            <ResponseContent>
                <Parameter/>
                <Document>
                    <RecordSet id="1">
                        <Master name="Master">
                            <Record>
${tableData.map(field => 
  `                                <Field name="${field.field}" value=""/>`
).join('\n')}
                            </Record>
                        </Master>
                    </RecordSet>
                    <RecordSet id="2">
                        <Master name="Master">
                            <Record>
${tableData.map(field => 
  `                                <Field name="${field.field}" value=""/>`
).join('\n')}
                            </Record>
                        </Master>
                    </RecordSet>
                </Document>
            </ResponseContent>
        </Response>
    }
    `;

    generatedCode.value = code;
    return code;
  };

  return {
    generateQueryApiCode,
    generatedCode
  };
}